package com.breeze.components.core.util.spring;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Optional;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

/**
 * @author breeze
 */
@Component
public class SpElUtil {

  private static final ExpressionParser PARSER = new SpelExpressionParser();
  private static final DefaultParameterNameDiscoverer PARAMETER_NAME_DISCOVERER =
      new DefaultParameterNameDiscoverer();
  private static BeanFactory beanFactory;

  public static Object[] parseSpEl(Method method, Object[] args, String[] spEls) {
    String[] params =
        Optional.ofNullable(PARAMETER_NAME_DISCOVERER.getParameterNames(method))
            .orElse(new String[] {});
    // el解析需要的上下文对象
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setBeanResolver(new BeanFactoryResolver(beanFactory));
    for (int i = 0; i < params.length; i++) {
      context.setVariable(params[i], args[i]);
    }
    return Arrays.stream(spEls)
        .map(spEl -> PARSER.parseExpression(spEl).getValue(context, String.class))
        .toArray();
  }

  @Autowired
  public void setBeanFactory(BeanFactory beanFactory) {
    SpElUtil.beanFactory = beanFactory;
  }
}
